package com.leyou.item.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.leyou.item.dto.CategoryDTO;
import com.leyou.item.entity.Category;
import com.leyou.item.entity.CategoryBrand;
import com.leyou.item.mapper.CategoryMapper;
import com.leyou.item.service.CategoryBrandService;
import com.leyou.item.service.CategoryService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.stream.Collectors;

@Service
public class CategoryServiceImpl extends ServiceImpl<CategoryMapper, Category> implements CategoryService {

    @Autowired
    private CategoryBrandService categoryBrandService;

    @Override
    public List<CategoryDTO> queryCategoryByBrandId(Long brandId) {
        // 查询中间表 SELECT * FROM tb_category_brand WHERE brand_id = 18374
        List<CategoryBrand> categoryBrandList = categoryBrandService.query().eq("brand_id", brandId).list();

        // 从查询结果CategoryBrand获取分类id
        List<Long> ids = categoryBrandList.stream()
                .map(categoryBrand -> categoryBrand.getCategoryId())
                .collect(Collectors.toList());
        // 查询分类表 SELECT * FROM tb_category WHERE id IN (?...)

        //两种写法
        List<Category> categoryList = this.listByIds(ids);
        //List<Category> categoryList = this.query().in("id", ids).list();

        // 转换DTO
        List<CategoryDTO> categoryDTOList = CategoryDTO.convertEntityList(categoryList);
        return categoryDTOList;
    }
}
